import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/models/book/BookQuizQuestion.dart';
import 'package:ichinesereader/models/book/MaxScore.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';

class MaxQuizDialog extends StatefulWidget {
  MaxQuizDialog({Key? key, required this.bookId, required this.maxScore})
      : super(key: key);
  final String bookId;
  final MaxScore maxScore;
  _MaxQuizDialog createState() => new _MaxQuizDialog();
}

class _MaxQuizDialog extends State<MaxQuizDialog> {
  ReportsController _reportsController = Get.find();
  final box = Hive.box('appconfig');

  int quizIndx = 0;
  bool loading = true;

  @override
  void initState() {
    setState(() {
      loading = true;
    });
    Future.delayed(Duration(milliseconds: 300), () {
      _reportsController.fetchBookQuiz(widget.bookId);
    }).then((result) {
      setState(() {
        loading = false;
      });
    });

    super.initState();
  }

  _getCloseButton(context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 10, 10, 0),
      child: GestureDetector(
        onTap: () {},
        child: Container(
          alignment: FractionalOffset.topRight,
          child: GestureDetector(
            child: Icon(
              Icons.clear,
              color: Colors.red,
            ),
            onTap: () {
              Navigator.pop(context);
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('Build max score quiz review page');
    return AlertDialog(
      title: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _getCloseButton(context),
              Padding(
                padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
                child: Obx(() {
                  if (_reportsController.bookquiz.value.questions != null) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Text(
                          'Score ${widget.maxScore.score} / ${_reportsController.bookquiz.value.questions!.length}',
                          style: Get.textTheme.titleMedium,
                          textAlign: TextAlign.center,
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        Text(
                          DateFormat('yyyy-MM-dd kk:mm').format(
                              DateTime.fromMillisecondsSinceEpoch(
                                  widget.maxScore.when!)),
                          style: Get.textTheme.bodySmall,
                          textAlign: TextAlign.center,
                        ),
                      ],
                    );
                  } else {
                    return Text('');
                  }
                }),
              )
            ],
          ),
        ),
      ),
      titleTextStyle: TextStyle(
          fontWeight: FontWeight.bold,
          letterSpacing: 1,
          color: Get.isDarkMode ? Color(0xffcccccc) : Colors.black,
          fontSize: 20),
      backgroundColor: Get.isDarkMode
          ? (Color(0xff333333))
          : Color.fromARGB(255, 234, 241, 238),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))),
      content: Container(
          height: 650,
          width: MediaQuery.of(context).size.width * 0.80,
          child: SingleChildScrollView(
            primary: false,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                loading
                    ? Center(
                        child: CircularProgressIndicator(
                        backgroundColor: Get.theme.primaryColorDark,
                        strokeWidth: 9.0,
                      ))
                    : Obx((() {
                        if (_reportsController.bookquiz.value.questions !=
                            null) {
                          return Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              for (int i = 0;
                                  i <
                                      _reportsController
                                          .bookquiz.value.questions!.length;
                                  i++)
                                _buildQuestionOption(
                                    _reportsController
                                        .bookquiz.value.baseResourceUrl!,
                                    _reportsController
                                        .bookquiz.value.questions![i],
                                    widget.maxScore,
                                    widget.maxScore.simple!,
                                    context)
                            ],
                          );
                        } else {
                          return Text('');
                        }
                      })),
              ],
            ),
          )),
    );
  }

  Container _buildQuestionOption(String baseUrl, QuizQuestion item,
      MaxScore answer, bool isSimplified, BuildContext context) {
    List<Widget> options = [];

    options.add(_buildHeadInfoWidget(baseUrl, item, isSimplified, context));
    options.add(SizedBox(height: 20));
    options.add(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Wrap(
            runSpacing: 30,
            spacing: 30,
            children: [
              for (int i = 0; i < item.answers!.length; i++)
                _buildOptionItem(
                    baseUrl,
                    item.answers![i],
                    i,
                    answer.submittedAnswers != null &&
                            answer.submittedAnswers![item.id] != null
                        ? answer.submittedAnswers![item.id]!.indexOf(
                                isSimplified
                                    ? item.answers![i].simpAnswer!
                                    : item.answers![i].tradAnswer!) >=
                            0
                        : false,
                    isSimplified,
                    context)
            ],
          )
        ],
      ),
    );

    return Container(
      //height: MediaQuery.of(context).size.height - 280,
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: options),
    );
  }

  Widget _buildHeadInfoWidget(String baseUrl, QuizQuestion element,
      bool isSimplified, BuildContext context) {
    return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Visibility(
              visible:
                  element.questionImage != null && element.questionImage != '',
              child: SizedBox(
                  width: MediaQuery.of(context).size.width * 0.6 > 400
                      ? 400
                      : MediaQuery.of(context).size.width * 0.6,
                  child:
                      Image.network(baseUrl + (element.questionImage ?? ''),fit: BoxFit.cover))),
          SizedBox(
              width: MediaQuery.of(context).size.width,
              child: RichText(
                  text: TextSpan(
                      text: isSimplified
                          ? (element.simpQuestion ?? '')
                          : (element.tradQuestion ?? ''),
                      style: TextStyle(
                          fontFamily: 'Noto Sans SC',
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: (Get.isDarkMode
                              ? Color(0xFF757575)
                              : Colors.black87),
                          height: 1.8),
                      children: [
                    WidgetSpan(
                        child: Visibility(
                            visible: element.questionAudio != null,
                            child: Container(
                                padding: EdgeInsets.fromLTRB(6, 4, 6, 0),
                                height: 40,
                                width: 52,
                                child: IconButton(
                                  iconSize: 40,
                                  padding: EdgeInsets.zero,
                                  icon: Icon(
                                    Icons.volume_up,
                                    color: Colors.orange,
                                  ),
                                  onPressed: () {
                                    BGSinglePlayer()
                                        .play(baseUrl + element.questionAudio!);
                                  },
                                ))))
                  ])))
        ]);
  }

  Widget _buildOptionItem(String baseUrl, QuizAnswer body, int index,
      bool isSelect, bool isSimplified, BuildContext context) {
    bool isCorrect = body.isCorrect ?? false;
    var widget = Row(
      children: [
        //圆形题号区
        Container(
          width: 30,
          height: 30,
          margin: EdgeInsets.symmetric(horizontal: 21),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Get.isDarkMode
                ? Get.theme.primaryColorDark
                : Get.theme.primaryColor,
          ),
          child: Text((index + 1).toString(),
              style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Get.isDarkMode
                      ? Colors.black
                      : Get.theme.primaryColorLight)),
        ),
        //句子+声音符号区
        Row(
          children: [
            Visibility(
                visible:
                    body.answerImage != null && body.answerImage!.isNotEmpty,
                child: SizedBox(
                    height: 160,
                    width: 160,
                    child: Image.network(baseUrl + (body.answerImage ?? "")))),
            RichText(
                text: TextSpan(
                    text: isSimplified
                        ? (body.simpAnswer ?? '')
                        : (body.tradAnswer ?? ''),
                    style: TextStyle(
                        fontSize: 18,
                        height: 1.8,
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.black),
                    children: [
                  WidgetSpan(
                      child: Visibility(
                          visible: body.answerAudio != null &&
                              body.answerAudio!.isNotEmpty,
                          child: Container(
                              padding: EdgeInsets.fromLTRB(6, 4, 6, 0),
                              height: 30,
                              width: 42,
                              child: IconButton(
                                iconSize: 30,
                                padding: EdgeInsets.zero,
                                icon: Icon(
                                  Icons.volume_up,
                                  color: Colors.orange,
                                ),
                                onPressed: () {
                                  BGSinglePlayer()
                                      .play(baseUrl + body.answerAudio!);
                                },
                              ))))
                ]))
          ],
        ),
      ],
    );
    return Container(
        child: widget,
        padding: EdgeInsets.only(top: 10, bottom: 10),
        width: (MediaQuery.of(context).size.width) * 0.8,
        decoration: BoxDecoration(
            color: isCorrect ? Color(0xffD9DDE8) : Colors.transparent,
            border: Border.all(
              color: isSelect
                  ? (isCorrect ? Color(0xFF39F210) : Color(0xFFF23030))
                  : Colors.transparent,
              width: 3,
            ),
            borderRadius: BorderRadius.circular(12)));
  }
}
